package cn.edu.sgu.www.pms.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.UUID;

/**
 * 密码加密器
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
public class PasswordEncoder {

    /**
     * 对用户提供的密码进行加密
     * @param password 用户提供的密码
     * @return String 加密后的密码
     */
    public static String encode(String password) {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String encodedPassword = password;

        for (int i = 0; i < 5; i++) {
            encodedPassword = DigestUtils.md5DigestAsHex(
                    (salt + encodedPassword + salt + salt + encodedPassword + salt + salt + salt).getBytes()
            );
        }

        return salt + encodedPassword;
    }

    /**
     * 匹配密码
     * @param password 用户提供的密码
     * @param encodedPassword 加密后的密码
     * @return boolean 密码匹配返回true，否则返回false
     */
    public static boolean matches(String password, String encodedPassword) {
        String salt = null;

        try {
            // 获取盐
            salt = encodedPassword.substring(0, 32);
        } catch (StringIndexOutOfBoundsException e) {
            log.debug("密码格式错误：password = {}", encodedPassword);

            e.printStackTrace();
        }

        String newPassword = password;

        for (int i = 0; i < 5; i++) {
            newPassword = DigestUtils.md5DigestAsHex(
                    (salt + newPassword + salt + salt + newPassword + salt + salt + salt).getBytes()
            );
        }
        newPassword = salt + newPassword;

        return newPassword.equals(encodedPassword);
    }

    public static void main(String[] args) {
        String password = "mhxy1218";

        System.out.println(encode(password));
    }

}